const express = require('express');
const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs');

const app = express();
app.use(express.json());

async function generatePDF(url, options = {}) {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  const timeout = process.env.PDF_TIMEOUT || 8000;
  await page.setDefaultTimeout(timeout);

  await page.goto(url, { waitUntil: 'networkidle0' });

  const defaultOptions = {
    path: path.join(__dirname, 'pdfs', `${Date.now()}.pdf`),
    format: 'A4',
    printBackground: true,
    margin: { top: '60px', right: '10px', bottom: '10px', left: '60px' },
    landscape: false,
    scale: 1.0
  };

  const finalOptions = { ...defaultOptions, ...options };

  await page.pdf(finalOptions);
  await browser.close();

  return finalOptions.path;
}

app.post('/generate-pdf', async (req, res) => {
  try {
    const { url, options } = req.body;
    if (!url) return res.status(400).send('URL is required');

    const outputPath = await generatePDF(url, options);
    res.status(200).json({ success: true, filePath: outputPath });
  } catch (err) {
    console.error('Error generating PDF:', err);
    res.status(500).json({ error: err.message });
  }
});

// 新增下载路由
app.get('/download/:filename', (req, res) => {
  const filePath = path.join(__dirname, 'pdfs', req.params.filename);
  res.download(filePath, (err) => {
    if (err) {
      console.error('Download error:', err);
      res.status(500).send('Download failed');
    } else {
      // 下载后删除文件
      fs.unlink(filePath, (err) => {
        if (err) console.error('Failed to delete:', err);
      });
    }
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`PDF API server running on port ${PORT}`);
});
